package com.changgou.oauth.controller;

import com.changgou.oauth.service.UserLoginService;
import com.changgou.oauth.util.AuthToken;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: wzw
 * @Date: 2020/12/22 15:50
 * @version: 1.8
 */
@RestController
@RequestMapping("/user")
public class UserLoginController {

    //获取客户端账号
    @Value("${auth.clientId}")
    private String clientId;

    //获取客户端密码(秘钥)
    @Value("${auth.clientSecret}")
    private String clientSecret;

    //注入service
    @Autowired
    private UserLoginService userLoginService;

    /**
     * @author wzw
     * 用户登录
     * @Date 16:22 2020/12/22
     * @param username 账号
     * @param password  密码
     * @return java.util.Map<java.lang.String,java.lang.Object>
    **/
    @RequestMapping("/login")
    public Result login(String username, String password, HttpServletResponse response){
        try {
            //1.固定格式:授权方式
            String grant_type = "password";

            //2.实现功能:登录认证
            AuthToken authToken = userLoginService.login(username, password, clientId, clientSecret, grant_type);

            //2.1存储token(令牌)到Cookie中(key,value)
            Cookie cookie = new Cookie("Authorization",authToken.getAccessToken());
            //2.2设置范围
            cookie.setPath("/");
            //2.3设置地址
            cookie.setDomain("localhost");
            //2.4添加响应的到Cookie中
            response.addCookie(cookie);

            //3.返回令牌
            return new Result(true, StatusCode.OK,"登录成功",authToken);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.LOGINERROR,"登录失败:"+e.getLocalizedMessage());
        }

    }
}
